package com.example.demo02;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.File;
import java.lang.reflect.Array;
import java.util.Arrays;

@SpringBootApplication
@EnableAsync
@EnableScheduling
public class Demo02Application {
    private static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        context=SpringApplication.run(Demo02Application.class, initLoggingPathArgs(args));
//        System.out.println(context.getEnvironment().getProperty("logging.dir"));
//        for (String arg : args) {
//            System.out.println(arg);
//        }
    }

    public static void restart() {
        ApplicationArguments args = context.getBean(ApplicationArguments.class);

        Thread thread = new Thread(() -> {
            context.close();
            context = SpringApplication.run(Demo02Application.class, args.getSourceArgs());
        });

        thread.setDaemon(false);
        thread.start();
    }

    public static String[] initLoggingPathArgs(String[] args){
        String loggingCommand=initializeLoggingPath();
        if(ArrayUtil.contains(args,loggingCommand)){
            return args;
        }
        return ArrayUtil.append(args,loggingCommand);
    }

    private static String initializeLoggingPath() {
        String exportPath;
        OsInfo osInfo = SystemUtil.getOsInfo();
        if(osInfo.isLinux()){
            exportPath="/var/log/demo02";
        }else {
            String projectPath = SystemUtil.get("user.dir");
            exportPath=new File(projectPath).getParent()+File.separator+"logs"+File.separator+"demo02";
        }
        return "--logging.dir="+exportPath;
    }


}
